#include "descriptorManager.h"
#include "common.h"
#include "termlist.h"


int main(int argc, char** argv) {
  log_init();
  g_log_context.log_level = LOG_DEBUG;
  int ret;

  FILE* fp = fopen(argv[1], "r");assert(fp);

  idx_head_t head;
  idx_index_t* index;
  idx_count_t* count;
  offset_t* offset;
  uint32_t lid = 0;

  while(1) {
    lid = 0;
    ret = fread(&head, sizeof(idx_head_t), 1, fp);
    if(ret != 1 && feof(fp)) {
      NOTICE("succ check idx status");
      exit(0);
    }
    else if(ret != 1) assert(0);

    index = (idx_index_t*)malloc(head.num_idx*sizeof(idx_index_t));
    assert(index);
    count = (idx_count_t*)malloc(head.num_idx*sizeof(idx_count_t));
    assert(count);
    offset = (offset_t*)malloc(head.num_off*sizeof(offset_t));
    assert(offset);


    ret = fread(index, sizeof(idx_index_t), head.num_idx, fp);
    assert(ret == (int)head.num_idx);

    ret = fread(count, sizeof(idx_count_t), head.num_idx, fp);
    assert(ret == (int)head.num_idx);

    ret = fread(offset, sizeof(offset_t), head.num_off, fp);
    assert(ret == (int)head.num_off);

    //NOTICE("--------head idx[%u], off[%u], tsign[%lu]---------", head.num_idx, head.num_off, head.tsign);
    for(uint32_t i = 0 ; i < head.num_idx ; ++i) {
      if(index[i].id < lid) {
	FATAL("error:idx not sorted: sign[%llu] num_idx[%d] num_off[%d] num[%d] id[%d], lastid[%d]",
	    head.tsign,
	    head.num_idx,
	    head.num_off,
	    i,
	    index[i].id,
	    lid);
	exit(-1);
      }
      lid = index[i].id;

      //offset check
      idx_count_t* ptc = &count[i];
      int ttype = 0;
      int toffset = 0;
      for(uint32_t j = 0; j < ptc->num ; ++j) {
	offset_t* poff = &offset[ptc->off + j];
	if(poff->texttype < ttype) {
	  FATAL("error:offset-texttype not sorted:sign[%llu] num_idx[%d] num_off[%d] num[%d] id[%d] off[%d]",
	      head.tsign,
	      head.num_idx,
	      head.num_off,
	      i,
	      index[i].id,
	      j);
	  exit(-1);
	}
	else if(poff->texttype == ttype) {
	  if(poff->offset < toffset) {
	    FATAL("error:offset-offset not sorted:sign[%llu] num_idx[%d] num_off[%d] num[%d] id[%d] off[%d]",
		head.tsign,
		head.num_idx,
		head.num_off,
		i,
		index[i].id,
		j);
	    exit(-1);
	  }
	}
	ttype = poff->texttype;
	toffset = poff->offset;
      }
    }
  }

  return 0;
}

